import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';
import * as bcrypt from 'bcrypt';

const prisma = new PrismaClient();

interface Question {
  type: string;
  content: string;
  options: string[];
  answer: string;
  explanation: string;
  subject: string;
  score: number;
}

interface SubjectQuestions {
  subject: string;
  questions: Question[];
}

async function loadQuestions(subject: string): Promise<SubjectQuestions> {
  const filePath = path.join(__dirname, 'questions', `${subject.toLowerCase()}.json`);
  const fileContent = fs.readFileSync(filePath, 'utf-8');
  const data: SubjectQuestions = JSON.parse(fileContent);
  return data;
}

async function main() {
  try {
    // 清空现有数据
    console.log('清空现有数据...');
    await prisma.answer.deleteMany();
    await prisma.examResult.deleteMany();
    await prisma.question.deleteMany();
    await prisma.exam.deleteMany();
    await prisma.user.deleteMany();
    console.log('数据库已清空');

    // 创建一个教师用户
    console.log('创建教师用户...');
    const hashedTeacherPassword = await bcrypt.hash('123456', 10);
    const teacher = await prisma.user.create({
      data: {
        username: 'teacher',
        email: 'teacher@example.com',
        password: hashedTeacherPassword,
        role: 'TEACHER'
      }
    });
    console.log('教师用户创建成功');

    // 创建一个学生用户
    console.log('创建学生用户...');
    const hashedStudentPassword = await bcrypt.hash('123456', 10);
    const student = await prisma.user.create({
      data: {
        username: 'student',
        email: 'student@example.com',
        password: hashedStudentPassword,
        role: 'STUDENT'
      }
    });
    console.log('学生用户创建成功');


    const subjects = ['chinese', 'math', 'english', 'physics', 'chemistry', 'biology', 'history', 'geography', 'politics'];
    const examSubjects = ['语文', '数学', '英语', '物理', '化学', '生物', '历史', '地理', '政治'];

    for (const subject of subjects) {
      console.log(`开始处理${subject}科目题目...`);
      try {
        const subjectQuestions = await loadQuestions(subject);
        console.log(`成功加载${subjectQuestions.questions.length}道${subject}题目`);
        
        // 批量创建题目
        for (const question of subjectQuestions.questions) {
          try {
            const questionData = {
              type: question.type || 'CHOICE',
              content: question.content,
              options: Array.isArray(question.options) ? JSON.stringify(question.options) : '[]',
              answer: question.answer,
              explanation: question.explanation || '',
              subject: subjectQuestions.subject,
              score: question.score || 1.0,
              createdBy: {
                connect: { id: teacher.id }
              }
            };

            await prisma.question.create({
              data: questionData
            });
          } catch (error) {
            console.error(`创建题目失败: ${question.content}`);
            console.error('错误详情:', error);
            continue;
          }
        }

        console.log(`${subject}科目题目创建完成！`);
      } catch (error) {
        console.error(`处理${subject}科目题目时出错:`, error);
        continue;
      }
    }

    // 为每个科目创建一场考试
    console.log('开始创建默认考试...');
    const now = new Date();
    for (const subject of examSubjects) {
      console.log(`开始创建${subject}科目的考试...`);
      try {
        // 获取该科目的所有题目
        const questions = await prisma.question.findMany({
          where: { subject: subject }
        });
        console.log(`找到${questions.length}道${subject}科目的题目`);

        if (questions.length > 0) {
          // 随机选择5道题目
          const selectedQuestions = questions
            .sort(() => Math.random() - 0.5)
            .slice(0, 5);
          console.log(`已随机选择${selectedQuestions.length}道题目`);

          // 计算总分
          const totalScore = selectedQuestions.reduce((sum, q) => sum + q.score, 0);
          const passingScore = Math.floor(totalScore * 0.6); // 60%为及格分数
          console.log(`考试总分：${totalScore}，及格分数：${passingScore}`);

          // 创建考试
          const examData = {
            title: `${subject}考试`,
            subject: subject,
            description: `这是一场${subject}考试，总共5道题目，请认真作答。`,
            startTime: new Date(now.getTime() ), // 明天开始
            endTime: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000), // 一周后结束
            duration: 60, // 60分钟
            totalScore: totalScore,
            passingScore: passingScore,
            createdBy: {
              connect: { id: teacher.id }
            },
            questions: {
              connect: selectedQuestions.map(q => ({ id: q.id }))
            }
          };

          console.log('准备创建考试，数据：', JSON.stringify(examData, null, 2));
          const exam = await prisma.exam.create({
            data: examData,
            include: {
              questions: true,
              createdBy: true
            }
          });

          console.log(`${subject}考试创建成功！考试ID：${exam.id}`);
        } else {
          console.log(`${subject}科目没有可用的题目，跳过创建考试`);
        }
      } catch (error) {
        console.error(`创建${subject}考试时出错:`, error);
        continue;
      }
    }

    console.log('默认考试创建完成！');

    console.log('数据库种子数据创建成功！');
  } catch (error) {
    console.error('初始化数据库失败:', error);
    throw error;
  }
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });